package com.xinnet.mms.customtransfer.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.common.AppGlobalContainer;
import com.xinnet.mms.customerManage.dao.CustomerManageDao;
import com.xinnet.mms.customerstate.dao.CustomerStateHistDao;
import com.xinnet.mms.customtransfer.service.RetrieveCustomTransferService;
import com.xinnet.mms.empcustomrelation.dao.EmpCustomRelationDao;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.entity.Product;
import com.xinnet.mms.entity.PublicConfig;
import com.xinnet.mms.utils.CustomerManage;

@Service("retrieveCustomTransferService")
public class RetrieveCustomTransferServiceImpl implements RetrieveCustomTransferService{
	
	@Autowired
	private EmpCustomRelationDao empCustomRelationDao;
	@Autowired
	private CustomerManageDao customerManageDao;
	@Autowired
	private CustomAllotService customAllotService;
	@Autowired
	private CustomerStateHistDao customerStateHistDao;
	
	private static Logger log=LoggerFactory.getLogger(RetrieveCustomTransferServiceImpl.class);
	
	/**
	 * 回收客户流转
	 */
	public void retrieveCustomTransfer() throws Exception{
		//获取产品规则
		Map<String,Product> productRuleMap = AppGlobalContainer.productRuleMap;
		if(productRuleMap==null || productRuleMap.isEmpty()){
			return;
		}
		/*//获取客户
		Map<Integer,List<EmpCustomRelation>> customerMap = (Map<Integer,List<EmpCustomRelation>>)AppGlobalContainer.transferCustomMap;
		if(customerMap==null || customerMap.isEmpty()){
			return;
		}
		List<EmpCustomRelation> retrieveCustomList = customerMap.get(CustomerManage.RECYCLING_CUSTOMER);
		if(retrieveCustomList==null || retrieveCustomList.isEmpty()){
			log.info("回收客户为空");
			return;
		}*/
        String isTest = ConfigUtil.getString("isTest");
        if(isTest==null || "".equals(isTest)){
        	log.error("配置异常：是否是测试环境");
        	return;
        }
        log.info("************************************************************************************回收客户流转开始********************************************");
        
        //回收客户流转
        //分页获取新注册客户信息
        Customer customer = new Customer();
        customer.setCustomType(CustomerManage.RECYCLING_CUSTOMER);
        int count = empCustomRelationDao.getTransferCustomCount(customer);
        
        PageView<Customer> page = new PageView<Customer>();
        page.setPageSize(50000); //每页显示5w条
        page.setRowCount(count);
        long pageCount = page.getPageCount();
        
        for(int i = 1;i<=pageCount;i++){
        	page.setPageNow(i);
        	Integer startPage = page.getFirstResult();
    		customer.setLimitTop(startPage);
    		customer.setLimitDown(page.getPageSize());
        	
        	List<EmpCustomRelation> retrieveCustomList = empCustomRelationDao.getTransferCustom(customer);
        	for (Iterator<EmpCustomRelation> iterator = retrieveCustomList.iterator(); iterator.hasNext();){
    			EmpCustomRelation retrieveCustom = (EmpCustomRelation) iterator.next();
    			this.customTransferForRetrieveCustomer(retrieveCustom, isTest);
    		}
        }
		
		log.info("************************************************************************************回收客户流转结束********************************************");
	}
	
	
	
	
	/**
	 * 对每个回收客户流转
	 * @param newRegisterCustom
	 * @param isTest
	 * @param transferRuleList
	 * @throws Exception
	 */
	@Transactional(propagation=Propagation.REQUIRES_NEW,readOnly=false,rollbackFor=Exception.class)
	public void customTransferForRetrieveCustomer(EmpCustomRelation retrieveCustom,String isTest){
		String customId = retrieveCustom.getCustomId();
		
		try {
			Customer customer = customAllotService.getCustomerById(customId);
			String productId = retrieveCustom.getProductId();
			if(productId==null||"".equals(productId)){
				productId = customAllotService.getDefaultProduct().getId();
			}
			
			if(productId==null || "".equals(productId)){
				log.info("当前产品ID: is null  return");
				return;
			}
			String pushHistId = retrieveCustom.getPushHistId();
			java.util.Date createTime = retrieveCustom.getCreateTime();
			Product currentProductRule=AppGlobalContainer.productRuleMap.get(productId);
			if(currentProductRule==null){
				log.error("当前产品规则为空!"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				return;
			}
			//系统分配未成交停留时间
			Integer holdtime = currentProductRule.getSysallocationNodealholdtime();
			if(holdtime==null){
				return;
			}
			Calendar calendar=Calendar.getInstance();
			calendar.setTime(createTime);
			if("false".equals(isTest)){
				calendar.add(Calendar.DATE, holdtime);
			}else if("true".equals(isTest)){
				calendar.add(Calendar.MINUTE, holdtime);
			}else{
				return;
			}
			Date saleHoldTime=calendar.getTime();
			Date nowDate= new Date();
			if(nowDate.after(saleHoldTime)){
				//获取可用的业绩保留期
				/*Map<String,PublicConfig> scoreHoldDateMap = AppGlobalContainer.scoreHoldDateMap;
				PublicConfig  publicConfig = scoreHoldDateMap.get("scoreHoldTime");
				boolean isCanGoOpenSea = this.isCanGoOpenSeaByScoreHoldTime(publicConfig,customId);*/
				if(true){
					customer.setCustomerType(CustomerManage.OPEN_SEA_CUSTOMER);
					customerManageDao.updateCustomType(customer);
					customer.setPushHistId(pushHistId);
					customer.setDeptId(retrieveCustom.getDeptno());
					customer.setProductId(productId);
					customer.setEmpId(retrieveCustom.getEmpId());
					customAllotService.allot(customer,CustomerManage.OPEN_SEA_CUSTOMER);
				}
				
			}	
			
		} catch (Exception e) {
			log.error("回收客户流转异常：customer id"+customId+"  "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),e);
			
		}

	}
	
	/**
	 * 根据业绩保留期 客户是否可以进入公海
	 * @param publicConfig
	 * @param createTime
	 * @return
	 */
	private boolean isCanGoOpenSeaByScoreHoldTime(PublicConfig publicConfig,String customId){
		if(publicConfig==null){
			return true;
		}
		String scoreHoldTime = publicConfig.getConfigValue();
		if(scoreHoldTime==null || "".equals(scoreHoldTime)){
			return true;
		}
		boolean isCanGoOpenSea = customerStateHistDao.isCanGoOpenSeaByScoreHoldTime(customId,scoreHoldTime);
		return isCanGoOpenSea;
	}
}
